package de.se.ludoapp.activity.task;

import android.os.AsyncTask;
import android.widget.ListView;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.NewGameActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameResponse;

/**
 * Task to accept an user for game.
 * 
 * @author Marlen Rotert
 * 
 */
public class AcceptRequestTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private NewGameActivity context;
	private String acceptPlayerName;

	public AcceptRequestTask(LudoApplication ludoApp, NewGameActivity context,
			String acceptPlayerName) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.acceptPlayerName = acceptPlayerName;
	}

	/**
	 * accept user sent on server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute allowUserToEnterTheGame */
		GameResponse gameResponse = ludoApp.getLudoStub()
				.allowUserToEnterTheGame(
						ludoApp.getlogedinUser().getSessionId(),
						acceptPlayerName, ludoApp.getCurrentGame().getGameId());
		if (gameResponse.getReturnCode() == 0) {
			Game game = gameResponse.getGame();
			ludoApp.setCurrentGame(game);
		}
		return gameResponse.getMsg();
	}

	/**
	 * update gameinfos in view. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		Game game = ludoApp.getCurrentGame();
		if (game != null) {
			final ListView listViewPlayerRequests = (ListView) context
					.findViewById(R.id.listViewNewGamePlayerRequests);
			listViewPlayerRequests.setEnabled(true);
			context.updateView();
			if (game.getNameYellowPlayer() != ""
					&& game.getNameRedPlayer() != ""
					&& game.getNameGreenPlayer() != ""
					&& game.getNameBluePlayer() != "") {
				new StartGameTask(ludoApp, context).execute();
			}
		}
	}
}
